const canvas = document.getElementById('snakeCanvas');
const ctx = canvas.getContext('2d');

let snake = [{x: 10, y: 10}];
let food = {x: 20, y: 20};
let dx = 10;
let dy = 0;
let speed = 150; // 移动速度（毫秒）
let score = 0;
let gridSize=1;

function drawSnakePart(snakePart) {
    ctx.fillStyle = "#0f0";
    ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
}

function drawFood() {
    ctx.fillStyle = "#f00";
    ctx.fillRect(food.x, food.y, 10, 10);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    snake.forEach(drawSnakePart);
    drawFood();
}

function changeDirection(event) {
    const keyPressed = event.keyCode;
    const goingUp = dy === -10;
    const goingDown = dy === 10;
    const goingRight = dx === 10;
    const goingLeft = dx === -10;
    if ((keyPressed === 38 && !goingDown) || (keyPressed === 87 && !goingDown)) {
        dy = -10;
        dx = 0;
    } else if ((keyPressed === 40 && !goingUp) || (keyPressed === 83 && !goingUp)) {
        dy = 10;
        dx = 0;
    } else if ((keyPressed === 39 && !goingLeft) || (keyPressed === 68 && !goingLeft)) {
        dx = 10;
        dy = 0;
    } else if ((keyPressed === 37 && !goingRight) || (keyPressed === 65 && !goingRight)) {
        dx = -10;
        dy = 0;
    }
}

document.getElementById('startButton').addEventListener('click', startGame);

function gameLoop() {
    // 更新蛇的位置
    const head = {x: snake[0].x + dx, y: snake[0].y + dy};
    snake.unshift(head);

    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        score+=100;
        updateScoreDisplay(); // 假设这是更新分数显示的函数
        generateFood();
    } else {
        snake.pop();
    }

    // 检查碰撞
    // 与自身碰撞检测
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver(); // 游戏结束处理
            return;
        }
    }
    // 与边界碰撞检测，假设canvas边界就是游戏边界
    if (head.x < 0 || head.x >= canvas.width / gridSize || head.y < 0 || head.y >= canvas.height / gridSize) {
        gameOver(); // 游戏结束处理
        return;
    }

    draw();
    setTimeout(gameLoop, speed);
}

// 添加辅助函数
function updateScoreDisplay() {
    // 这里根据你的UI实现来更新显示的分数，例如：
    document.getElementById('scoreDisplay').innerText = score;
}

function gameOver() {
    // 显示游戏结束信息，重置游戏状态等操作
    alert("Game Over! Your score is " + score);
    // 可能还需要重置游戏状态，如：snake, score, dx, dy, food位置等
    snake = [{x: 15, y: 15}]; // 举例，初始化蛇的位置
    score = 0;
    dx = dy = gridSize; // 举例，重置速度方向
    generateFood(); // 重新生成食物
    // 根据需要还可以添加重玩按钮的逻辑等
}

function generateFood() {
    // 随机生成食物位置
    food = {x: Math.floor(Math.random() * 39) * 10, y: Math.floor(Math.random() * 39) * 10};
}

function startGame() {
    gameLoop();
    document.addEventListener('keydown', changeDirection);
}